package com.itboye.api.domain;


import com.itboye.api.model.ByResponseData;
import com.itboye.mybatis.enumtype.CodeType;
import com.itboye.mybatis.enumtype.DataStatus;
import com.itboye.mybatis.enumtype.UserRoles;
import com.itboye.mybatis.model.MemberModel;
import com.itboye.mybatis.model.UcenterMemberModel;
import com.itboye.mybatis.viewmodel.AccountViewModel;
import com.itboye.mybatis.viewmodel.UserAuthGroupAccessViewModel;
import com.itboye.services.ucenter.facade.AccountService;
import com.itboye.services.ucenter.interfaces.IAccountService;
import com.itboye.services.ucenter.interfaces.IMemberService;
import com.itboye.services.ucenter.interfaces.IUcenterMemberService;
import com.itboye.services.utils.impl.SecurityCodeService;
import com.itboye.services.utils.interfaces.ISecurityCodeService;
import com.itboye.system.bean.ByResultBean;
import com.itboye.system.crypt.ByPasswordCrypt;
import com.itboye.system.exception.ByBaseException;
import com.itboye.system.helper.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 与用户相关的领域模型
 * Created by hebidu on 16/5/11.
 */
@Component("UserDomain")
public class UserDomain extends BaseDomain {

    private static final Logger logger = LogManager.getLogger(UserDomain.class.toString());

    @Resource
    private IAccountService accountService;

    @Resource
    private IMemberService memberService;

    @Resource
    private IUcenterMemberService ucenterMemberService;

    @Resource
    private ISecurityCodeService securityCodeService;

    public UserDomain(){
        super();
        ByConsoleHelper.debug("UserDomain 构造函数",logger);
    }

    /**
     * 用户更新接口
     * @return
     */
    public ByResponseData update() throws ByBaseException, UnsupportedEncodingException {
        ByConsoleHelper.debug("调用用户更新接口", logger);
        //1. 检测版本
        this.checkApiVersion("102");
        ByConsoleHelper.debug("用户更新接口版本检测通过", logger);
        String strUid = this.getStringParam("uid");
        assertNotNull(strUid, "UID不能为空");
        int uid = 0;
        try {
            uid = Integer.parseInt(strUid);
        } catch (NumberFormatException e) {
            return fail("uid非法");
        }

        String nickname = this.getStringParam("nickname");
        String email = this.getStringParam("email");
        HashMap<String, String> params = new HashMap<String, String>();


        if (nickname != null && nickname.length() > 0) {
            //有值的情况下,才更新
            params.put("uid", "" + uid);
            params.put("nickname", nickname);
            memberService.update(params);
        }

        params.clear();

        if (email != null && email.length() > 0) {
            if(!ByRegExpHelper.isEmail(email)){
                return fail("邮箱格式不正确");
            }
            params.put("id", "" + uid);
            params.put("email", email);
            ucenterMemberService.update(params);
        }

        return success("更新成功");
    }

    /**
     * 用户登录接口
     * 1. [100] 初步完成用户登录接口
     * 2. [101] 返回数据中增加了用户组信息
     * 3. [102] 返回增加企业用户认证标志is_auth_e字段
     * @return
     * @throws UnsupportedEncodingException
     * @throws ByBaseException
     */
    public ByResponseData login() throws UnsupportedEncodingException, ByBaseException, NoSuchAlgorithmException {

        ByConsoleHelper.debug("调用登录接口",logger);
        //1. 检测版本
        this.checkApiVersion("103");
        ByConsoleHelper.debug("登录接口版本检测通过",logger);

        //2. 准备参数
        String username = this.getStringParam("username");
        String password = this.getStringParam("password");
        Integer    userRoles= this.getIntegerParam("role");
        UserRoles roles = UserRoles.UNKNOWN;
        if(userRoles != null){
            roles = UserRoles.getUserRoles(userRoles.intValue());
        }

        assertNotNull(username,"用户名不能为空");
        assertNotNull(password,"密码不能为空");

        ByConsoleHelper.debug("username="+username,logger);
        ByConsoleHelper.debug("password="+password,logger);

        HashMap<String,String> map = new HashMap<String,String>();

        if(ByRegExpHelper.isMobile(username)){
            map.put("mobile",username);
        }else {
            map.put("username", username);
        }

        if(memberService == null) {
            ByConsoleHelper.debug("memberService is null",logger);
        }

        AccountViewModel accountViewModel = accountService.getInfoBy(map);

        if(accountViewModel == null){
            return fail("该帐号尚未注册");
        }

        String salt = ByConfigHelper.getInstance().getPasswordSalt();
        String encodePwd = ByPasswordCrypt.encode(password,salt);

        if(accountViewModel.getPassword().equals(encodePwd)) {

            for (UserAuthGroupAccessViewModel access:accountViewModel.getAuthGroupModelList()){
                if(access.getUserRoles() == roles){
                    return  success(accountViewModel);
                }
            }

            return fail("登录失败");
        }

        return  fail("帐号或密码错误");
    }

    /**
     * 用户注册
     * @return 用户信息
     * @throws ByBaseException
     */
    public ByResponseData register() throws ByBaseException, UnsupportedEncodingException, NoSuchAlgorithmException {
        ByConsoleHelper.debug("调用用户注册接口register",logger);
        //1. 检测版本
        this.checkApiVersion("101");
        ByConsoleHelper.debug("登录接口版本检测通过",logger);

        String username = this.getStringParam("username");
        String password = this.getStringParam("password");
        String code = this.getStringParam("code");
        Integer    userRoles= this.getIntegerParam("role");
        UserRoles roles = UserRoles.UNKNOWN;
        if(userRoles != null){
            roles = UserRoles.getUserRoles(userRoles);
        }
        if(roles == UserRoles.UNKNOWN) {
            roles = UserRoles.ENTERPRISE;
        }

        ByResultBean byResultBean = securityCodeService.isValid(code,username, CodeType.REGISTER);

        if(!byResultBean.isSuccess()){
            return fail(byResultBean.getMsg());
        }

        //参数数据

        Long timestamp = ByDateHelper.getCurrentTimeStamp();
        HttpServletRequest request = getRequest();
        String ip = "127.0.0.1";
        if(request != null){
            ip = ByIpHelper.getLocalIp(request);
        }
        Long longIp = ByIpHelper.ip2long(ip);

        //加密密码
        String encodePwd = ByPasswordCrypt.encode(password,ByConfigHelper.getInstance().getPasswordSalt());

        String mobile = "";

        if(!ByRegExpHelper.isLegalUserName(username)){
            return fail("用户名必须字母开头且大于6位小于32位长度");
        }

        //检测用户名是否已被注册
        HashMap<String,String> params = new HashMap<String, String>();

        if(ByRegExpHelper.isMobile(username)){
            mobile = username;
            username = "m_" + username;
            params.put("mobile", username);
        }else {
            params.put("username", username);
        }

        UcenterMemberModel ucenterMemberModel = ucenterMemberService.getInfoBy(params);
        if(ucenterMemberModel != null){
            return fail("用户名已被注册");
        }

        params.clear();
        params.put("username",username);
        ucenterMemberModel = ucenterMemberService.getInfoBy(params);
        if(ucenterMemberModel != null){
            return fail("用户名已被注册");
        }

        AccountViewModel accountViewModel = new AccountViewModel();
        accountViewModel.setUsername(username);
        accountViewModel.setPassword(encodePwd);
        accountViewModel.setStatus(DataStatus.NORMAL);
        accountViewModel.setEmail(username+"@by.com");
        accountViewModel.setUpdateTime(timestamp.intValue());
        accountViewModel.setLastLoginIp(longIp.toString());
        accountViewModel.setLastLoginTime(timestamp.toString());
        accountViewModel.setRegIp(longIp.toString());
        accountViewModel.setRegTime(timestamp.intValue());
        accountViewModel.setMobile(mobile);

        MemberModel memberModel = new MemberModel();

        memberModel.setSign("");
        memberModel.setAddUid(0);
        memberModel.setBirthday(timestamp.intValue());
        memberModel.setHead("");
        memberModel.setIdnumber("");
        memberModel.setLogin(0);
        memberModel.setNickname("昵称");
        memberModel.setRealname("");
        memberModel.setUpdateTime(timestamp.intValue());
        memberModel.setQq("");
        memberModel.setSex(0);
        memberModel.setScore("0");
        accountViewModel.setMemberModel(memberModel);

        List<UserAuthGroupAccessViewModel> list = new ArrayList<UserAuthGroupAccessViewModel>();

        UserAuthGroupAccessViewModel accessViewModel = new UserAuthGroupAccessViewModel();

        accessViewModel.setId(roles.getRoles());

        list.add(accessViewModel);

        accountViewModel.setAuthGroupModelList(list);

        int uid = accountService.insert(accountViewModel);

        if(uid > 0){
            return success(uid);
        }

        return fail("注册失败");
    }

}
